﻿Public Class MoveableWindow : Inherits MinimalistWindow

    Protected AllowOnLocationChanged As Boolean
    Public MainGrid As KGrid
    Protected humbleGrid As Grid
    Public MDG As MainDockGrid
    Public InjectedGrid As Grid

    Public Sub New(ByVal _TITLE As String,
                   ByVal _FRMRSZBRDRTKNS As Thickness,
                   ByVal _GLSFRMTKNS As Thickness,
                   ByVal _CRNRRADIUS As CornerRadius,
                   ByVal _TTLBRHEIGHT As Double,
                   ByRef _mdg As MainDockGrid)
        MyBase.New(_TITLE, _FRMRSZBRDRTKNS, _GLSFRMTKNS, _CRNRRADIUS, _TTLBRHEIGHT)

        MDG = _mdg

        humbleGrid = New Grid

        '   WindowStyle = Windows.WindowStyle.None


    End Sub

    Public Sub New(ByRef _mdg As MainDockGrid)
        MyBase.New()
        MDG = _mdg

        humbleGrid = New Grid

        ' WindowStyle = Windows.WindowStyle.None

    End Sub

    Public Sub New()

        MyBase.New()
        humbleGrid = New Grid


        ' WindowStyle = Windows.WindowStyle.None

    End Sub

    ''' <summary>
    ''' Carica la Finestra ma non la mostra
    ''' -
    ''' Loads the window, but doesn't show it.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Load()
        Show()      'chiama loaded.
        Hide()          'chiude subito la finestra.
    End Sub

    Public Sub MoveTo(ByVal X As Double, ByVal Y As Double)
        AllowOnLocationChanged = False
        Left = X  'TODO: Esiste un problema location changed viene chiamato dalla prima istruzione e poi dopo chiama la seconda. Dato che location changed chiude PuppetWindow, la seconda viene eseguita con un puppetwindow chiuso ovvero non più connesso alla PresentationSource.
        AllowOnLocationChanged = True
        Top = Y
    End Sub

    Public Sub MoveTo(ByVal location As Point)
        MoveTo(location.X, location.Y)
    End Sub

    Protected Overrides Sub OnLocationChanged(ByVal e As System.EventArgs)
        '  If AllowOnLocationChanged Then
        'Try
        Dim pToScreen As Point = PointToScreen(Mouse.GetPosition(Me))
        If MDG Is Nothing Or Not MDG.MyBoundsContainsPoint(pToScreen) Then Return

        MDG.ShiftGizmo(pToScreen)
        MDG.StartDockingProcedure(pToScreen, Nothing)


        ' Catch ex As Exception
        ' End Try
        MyBase.OnLocationChanged(e)
        ' End If
    End Sub

    Protected Overridable Sub TriggerTestForDocking(ByVal pToScreen As Point)
        If MDG Is Nothing Then Return
        Dim p As Point = pToScreen
        Dim landingGrid As Grid
        Dim dckpos As MainDockGrid.DockPosition = MDG.StartDockingProcedure(p, landingGrid)
        If landingGrid IsNot Nothing And dckpos <> MainDockGrid.DockPosition.Null Then
            'Dim detachingGrid As Grid
            'detachingGrid = MainGrid
            MDG.DockCard(MainGrid, landingGrid, dckpos, Me)
        End If
    End Sub

    Private Sub _Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        'queste istruzione servono a controllare che esista già almeno un maindockgrid da qualche parte nell'applicazione.
        'se esiste allora, quelo maindockgrid diventerà il maindockgrid di default per il dock e float di questa moveable window.
        Dim token As MainDockGrid.MainDockGridToken = Application.Current.Properties.Item("MDGToken")

        If token IsNot Nothing Then
            MDG = token.MDG


            If InjectedGrid IsNot Nothing Then
                ' MainGrid.ContentGrid.Children.Clear()

                If TypeOf (InjectedGrid) Is CentrKGrid Then
                    DirectCast(InjectedGrid, CentrKGrid).MDG = MDG
                ElseIf TypeOf (InjectedGrid) Is KGrid Then
                    DirectCast(InjectedGrid, KGrid).MDG = MDG
                End If

                'se il programmatore ha specificato un'altro grid da "iniettare" in questa moveable window, Maingrid sostituisce il suo contenuto con quello di InjectedGrid.
                MainGrid = InjectedGrid
                InjectedGrid = Nothing
            Else
                MainGrid = New KGrid(MDG)
                'MEGA ----|
                MainGrid.ContentGrid.Children.Clear()                   'cancella il contenuto di maingrid.
                Dim g As Object = Content                   'dichiara g come il contenuto di Content = ovvero il grid che viene definito dal programmatore in xaml.
                RemoveLogicalChild(Content)         'rimuove il contenuto dalla finestra.
                Content = Nothing                                   'cancella dalla memoria il pointer a Content.
                MainGrid.ContentGrid.Children.Add(g)                    'sposta il contenuto ( che ora è rappresentato da g ) dentro maingrid.
                ' |----->
                MainGrid.Title = Title
            End If



            '  MainGrid.Banner.ToggleIcon()


            MainGrid.Grip.PuppetWindow = Me     'questa istruziona compatissima permette a Grip di muovere come un pupazzo questa finestra.
            '   MainGrid.Grip.IsActive = False
            'BOUND ALL TO WINDOW
            humbleGrid.Children.Add(MainGrid)
            Content = humbleGrid 'A questo punto bisogna rendere BaseGrid il contenuto della MoveableWindow. Content era già stato tolto dalla finestra e dalla memoria, precedentemente.


            ' MainGrid.MDG = MDG
            'Try
            MDG.AdoptMoveableWindow(Me)

            AddHandler MainGrid.Grip.MouseUp, AddressOf onGripMouseUp
            AddHandler MainGrid.Banner.PART_LeftButton.Click, AddressOf onLeftButtonClick
            '  EnableElement(MainGrid.Banner.PART_LeftButton)
            AddHandler MainGrid.Banner.PART_MiddleButton.Click, AddressOf onMiddleButtonClick
            ' EnableElement(MainGrid.Banner.PART_MiddleButton)
            AddHandler MainGrid.Banner.PART_RightButton.Click, AddressOf onRightButtonClick
            ' EnableElement(MainGrid.Banner.PART_RightButton)

            EnableElement(MainGrid.Banner)
            MainGrid.State = KGrid.KGridState.Float

            '  Me.Background = MDG.Background
            'inietta l'icona nel grid.
            If MainGrid.Banner.PART_Icon.Source Is Nothing Then
                MainGrid.Banner.PART_Icon.Source = Icon
            End If

            MainGrid.Background = MDG.Background     'Valore di Default.

            '  humbleGrid.Margin = Me.Frame
            MainGrid.Banner.Margin = New Thickness(Frame.Left, Frame.Top, Frame.Right, 0)
            MainGrid.ContentGrid.Margin = New Thickness(Frame.Left, 0, Frame.Right, Frame.Bottom)


            EnableElement(MainGrid.ContentGrid)


        End If


    End Sub

    Private Sub _Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing

        RemoveHandler MainGrid.Grip.MouseUp, AddressOf onGripMouseUp

        RemoveHandler MainGrid.Banner.PART_LeftButton.Click, AddressOf onLeftButtonClick
        RemoveHandler MainGrid.Banner.PART_MiddleButton.Click, AddressOf onMiddleButtonClick
        RemoveHandler MainGrid.Banner.PART_RightButton.Click, AddressOf onRightButtonClick


        MDG.AbandonMoveableWindow(Me)
    End Sub



    Public Sub onLeftButtonClick(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)

    End Sub

    Public Sub onRightButtonClick(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        If Me.IsLoaded Then Me.Close()
    End Sub

    Public Sub onMiddleButtonClick(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)

    End Sub

    Private Sub onGripMouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        TriggerTestForDocking(PointToScreen(Mouse.GetPosition(Me)))
    End Sub

End Class

